﻿using System.Collections.Generic;
using Eneta.Portal.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Deployment
{
    public class CompanyListsReceiver: SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (var web = properties.Feature.Parent as SPWeb)
            {
                if (web == null)
                    return;
                AddFieldsToContentType("IOCompany", "Üksus", web);
                AddFieldsToContentType("IOLevel1", "Üksus", web);
                AddFieldsToContentType("IOLevel2", "Üksus", web);
                AddFieldsToContentType("IOProducts", "Üksus", web);
                AddFieldsToContentType("IOTopic", "Üksus", web);

                web.EnsureLookupField("IOLevel2", "IOLevel1", "Level1");
                web.EnsureLookupField("IOTopic", "IOProducts", "IOProducts");
                web.EnsureLookupField("IOTopic", "IOLevel2", "Level2");
                web.EnsureLookupField("IOCompany", "IOTopic", "IOTopic");
                web.EnsureLookupField("IOCompany", PublishingWeb.GetPagesListName(web), "Company");
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            
        }
        
        private void AddFieldsToContentType(string listName, string contentType, SPWeb web)
        {
            if (web == null)
                return;
            SPList list = web.Lists[listName];
            if (list == null)
                return;
            SPContentType cType = list.ContentTypes[contentType];
            if (cType == null)
                return;
            foreach (SPFieldLink link in GetFieldsToAdd(list, cType))
            {
                cType.FieldLinks.Add(link);
            }
            cType.Update();
        }

        private static List<SPFieldLink> GetFieldsToAdd(SPList list, SPContentType type)
        {
            var fields = new List<SPFieldLink>();
            foreach (SPField field in list.Fields)
            {
                if (!field.Hidden && !field.ReadOnlyField && !type.Fields.ContainsField(field.InternalName))
                {
                    fields.Add(new SPFieldLink(field));
                }
            }
            return fields;
        }
    }
}
